// components/upload-tool/upload.js
const mybehavior = require("../../behaviors/requests")
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [mybehavior],
  properties: {
    fs_upload_url: {
      type: String,
      value: "",
    },
    uploader: {
      type: Array,
      value: [],
    },
    img_count: {
      type: Number,
      value: 1
    },
    style: {
      type: String,
      value: "",
    },
    show:{
      type:Boolean,
      value:true
    },
    deletable:{
      type:Boolean,
      value:true
    },
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    handle_delete(e) {
      const index = e.detail.index;
      const file = this.data.uploader[index];
      const file_id = file.url.split("=")[1];
      const uploader = this.data.uploader;
      const self = this;

      let url1 = self.data.fs_upload_url + '/fs_delete'
      let data = {
        file_id
      }
      this.post(url1, data, true).then(res => {
        if (res.code == 20000) {
          wx.showToast({
            title: res.msg,
            icon: 'success'
          })
          uploader.splice(index, 1);
          self.setData({
            uploader,
          });
          self.triggerEvent("setValue", self.data.uploader);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    },

    // 照片选取
    try_upload(e) {
      const self = this;
      // 关闭照片选取
      // 确定还有张图片可以选择
      wx.chooseMedia({
        count: self.data.img_count,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          const myUploadFiles = res.tempFiles.map(tempFile => {
            const tempFilePath = tempFile.tempFilePath;
            return self.myUploadFile(tempFilePath);
          });
          wx.showLoading({
            title: '开始上传。。。',
          })

          Promise.all(myUploadFiles).then(file_ids => {
            wx.hideLoading();
            // 处理UI
            const uploader = self.data.uploader;

            const new_uploader = uploader.concat(file_ids.map(file_id => {
              return {
                url: self.data.fs_upload_url + '/fs_download?file_id=' + file_id,
                isImage: true,
                file_id: file_id

              };
            }));
            self.setData({
              uploader: new_uploader,
            })
            self.triggerEvent("setValue", self.data.uploader);
            wx.showToast({
              title: '上传成功！',
            });

          }).catch(msg => {
            wx.hideLoading();

            wx.showToast({
              title: msg,
              icon: "error"
            })
            console.log(msg);
          });
        },
        fail() {
        }
      })
    },

    myUploadFile(file) {
      let self = this
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: self.data.fs_upload_url + '/fs_upload',
          filePath: file,
          name: 'file',
          formData: {},
          success(res) {
            const result = JSON.parse(res.data);
            wx.hideLoading();
            if (result.code == 20000) {
              resolve(result.data.file_id);
            } else {
              reject(result.msg);
            }

          },
          fail() {
            reject("未知错误446");
          }
        })
      });
    },
  }
})
